package hankz.spring.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import hankz.spring.beans.BeansException;
import hankz.spring.beans.factory.DisposableBean;
import hankz.spring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @auther zzc
 * @date 2021 11 22
 */
public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;

    private final String beanName;

    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }


    @Override
    public void destroy() throws Exception {

        //1、实现接口
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        //2、配置
        if (StrUtil.isNotEmpty(destroyMethodName) && (!(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName)))) {
            Method method = bean.getClass().getMethod(destroyMethodName);
            if (null == method) {
                throw new BeansException("not found 404 ");
            }
            method.invoke(bean);
        }
    }
}
